package com.example.shop.cart

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.CarEntityResult
import com.example.base.entity.ResultEntity
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class CartViewModel :BaseViewModel(){
    val success = MutableLiveData<CarEntityResult>()
    val fail = MutableLiveData<String>()
    fun selectCar(){
        viewModelScope.launch {
            try {
                val result = apiServer.selectCar()
                success.value = result
            }catch (e:Exception){
                fail.value = e.message
            }
        }
    }
    val deleteSuccess = MutableLiveData<ResultEntity>()
    val deleteFail = MutableLiveData<String>()
    fun deleteCar(ids:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map["ids"] = ids
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                val result = apiServer.deleteCar(body)
                deleteSuccess.value = result
            }catch (e:Exception){
                deleteFail.value = e.message
            }
        }
    }

    val addSuccess = MutableLiveData<ResultEntity>()
    val addFail = MutableLiveData<String>()
    fun addCar(goodsId:Int,count:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Int>()
                map["goods_id"] = goodsId
                map["count"] = count
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                val result = apiServer.addCar(body)
                addSuccess.value = result
            }catch (e:Exception){
                addFail.value = e.message
            }
        }
    }
}